<template>
    <div>
        <el-card class="box-card" style="margin: 20px 30px; width: 95%">
            <el-input
                placeholder="请输入内容"
                size="small"
                style="width: 20%"
                v-model="searchVal"
            ></el-input>
            <el-button
                icon="el-icon-search"
                size="small"
                type="primary"
                style="margin-left: 30px"
                @click="searchClick"
                >查询</el-button
            >
            <el-button size="small" plain @click="clearSearch">清空</el-button>
            <br />
            <div style="margin-top: 20px">
                <el-button
                    size="small"
                    type="primary"
                    @click="dialogVisible = true"
                    >添加</el-button
                >
                <el-button size="small" type="warning" @click="mutiDeleteUser"
                    >批量删除</el-button
                >
            </div>

            <el-table
                @select="changeSelect"
                @select-all="changeSelectAll"
                :data="userList"
                border
                style="width: 100%; margin-top: 20px"
            >
                <el-table-column
                    align="center"
                    type="selection"
                    label="日期"
                    width="50"
                >
                </el-table-column>
                <el-table-column
                    align="center"
                    type="index"
                    label="序号"
                    width="60"
                >
                </el-table-column>
                <el-table-column prop="username" label="用户名" width="100">
                </el-table-column>
                <el-table-column prop="nickName" label="用户昵称" width="100">
                </el-table-column>
                <el-table-column prop="roleName" label="角色列表">
                </el-table-column>
                <el-table-column prop="gmtCreate" label="创建时间" width="180">
                </el-table-column>
                <el-table-column
                    prop="gmtModified"
                    label="更新时间"
                    width="180"
                >
                </el-table-column>
                <el-table-column
                    align="center"
                    prop="address"
                    label="操作"
                    width="200"
                >
                    <template slot-scope="scope">
                        <el-button
                            size="mini"
                            type="info"
                            icon="el-icon-user"
                            @click="getRoleInfo(scope.row)"
                        ></el-button>
                        <el-button
                            size="mini"
                            type="primary"
                            icon="el-icon-edit-outline"
                            @click="clickEditButton(scope.row)"
                        ></el-button>
                        <el-button
                            size="mini"
                            type="danger"
                            icon="el-icon-delete"
                            @click="deleteUser(scope.row.id)"
                        ></el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                :current-page.sync="currentPage"
                layout="prev, pager, next, jumper"
                :page-size="pageSize"
                :total="total"
                style="margin-top: 20px"
            >
            </el-pagination>
        </el-card>
        <!-- 添加修改框 -->
        <el-dialog
            :show-close="false"
            :close-on-click-modal="false"
            title="添加用户"
            :visible.sync="dialogVisible"
            width="60%"
        >
            <el-form
                :model="addUserData"
                :rules="rules"
                ref="ruleForm"
                label-width="80px"
            >
                <el-form-item label="用户名" prop="username">
                    <el-input
                        size="small"
                        v-model="addUserData.username"
                    ></el-input>
                </el-form-item>
                <el-form-item label="用户昵称" prop="nickName">
                    <el-input
                        size="small"
                        v-model="addUserData.nickName"
                    ></el-input>
                </el-form-item>
                <el-form-item
                    label="用户密码"
                    prop="password"
                    v-if="!addUserData.id"
                >
                    <el-input
                        size="small"
                        v-model="addUserData.password"
                    ></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="closeWindow">取 消</el-button>
                <el-button
                    size="small"
                    type="primary"
                    @click="clickAddorEditUser"
                    >确 定</el-button
                >
            </span>
        </el-dialog>
        <!-- 添加角色框 -->
        <el-dialog
            :show-close="false"
            :close-on-click-modal="false"
            title="设置角色"
            :visible.sync="dialogVisibleRole"
            width="70%"
        >
            <el-form label-width="80px">
                <el-form-item label="用户名">
                    <el-input
                        :placeholder="addUserData.username"
                        :disabled="true"
                    ></el-input>
                </el-form-item>
                <el-form-item label="角色列表">
                    <el-checkbox
                        :indeterminate="isIndeterminate"
                        v-model="checkAll"
                        @change="handleCheckAllChange"
                        >全选</el-checkbox
                    >
                    <div style="margin: 15px 0"></div>
                    <el-checkbox-group
                        v-model="assignRolesName"
                        @change="handleCheckedCitiesChange"
                    >
                        <el-checkbox
                            v-for="(roleName, index) in allRolesListName"
                            :label="roleName"
                            :key="index"
                            >{{ roleName }}</el-checkbox
                        >
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="cancelChangeUserRole"
                    >取 消</el-button
                >
                <el-button size="small" type="primary" @click="changeUserRole"
                    >确 定</el-button
                >
            </span>
        </el-dialog>
    </div>
</template>

<script>
import {
    reqGetUserList,
    reqSearchUserList,
    reqAddUser,
    reqEditUser,
    reqDeleteUser,
    reqGetRoleInfo,
    reqChangeUserRole,
    reqMutiDeleteUser,
} from "@/api/userMana";

export default {
    data() {
        return {
            selectedRow: [],
            checkAll: false,
            isIndeterminate: true,

            userList: [],
            currentPage: 1,
            // pageCount: 1,
            pageSize: 5,
            total: -1,
            searchVal: "",
            dialogVisible: false,
            addUserData: {
                id: "",
                password: "",
                nickName: "",
                username: "",
            },
            rules: {
                password: [
                    {
                        required: true,
                        message: "请输入密码",
                        trigger: "blur",
                    },
                ],
                username: [
                    {
                        required: true,
                        message: "请输入用户名",
                        trigger: "blur",
                    },
                ],
            },
            dialogVisibleRole: false,
            assignRoles: [],
            allRolesList: [],
            allRolesListName: [],
            assignRolesName: [],
        };
    },
    methods: {
        // 多选框
        handleCheckAllChange(val) {
            this.assignRolesName = val ? this.allRolesListName : [];
            this.isIndeterminate = false;
        },
        handleCheckedCitiesChange(value) {
            let checkedCount = value.length;
            this.checkAll = checkedCount === this.allRolesListName.length;
            this.isIndeterminate =
                checkedCount > 0 && checkedCount < this.allRolesListName.length;
        },

        // 初始化用户列表数据
        initData() {
            this.getUserList(this.currentPage, this.pageSize);
        },
        // 获取用户列表
        async getUserList(currentPage, pageSize) {
            try {
                const re = await reqGetUserList(currentPage, pageSize);
                this.userList = re.data.items;
                // this.pageCount = Math.ceil(re.data.total / this.pageSize);
                this.total = re.data.total;
                this.$notify.success("获取用户列表成功");
            } catch (error) {
                this.$notify.error(error.message);
            }
        },
        // 查询用户
        async searchUserList(currentPage, pageSize, username) {
            try {
                const re = await reqSearchUserList(
                    currentPage,
                    pageSize,
                    username
                );
                this.userList = re.data.items;
                this.total = re.data.total;
            } catch (error) {
                this.$notify.error(error.message);
            }
        },
        // 查询用户点击事件
        searchClick() {
            this.searchUserList(
                this.currentPage,
                this.pageSize,
                this.searchVal
            );
        },
        // 情况查询输入框
        clearSearch() {
            this.searchVal = "";
            this.initData();
        },
        // 点击确定，新增或修改用户事件
        async clickAddorEditUser() {
            try {
                if (this.addUserData.id) {
                    // 修改用户
                    await reqEditUser(this.addUserData);
                    this.initData();
                } else {
                    // 添加用户
                    await reqAddUser(this.addUserData);
                    this.initData();
                }
                this.addUserData = {
                    password: "",
                    username: "",
                    nickName: "",
                };
                this.dialogVisible = false;
                this.$notify.success("成功添加或修改用户");
            } catch (error) {
                this.$notify.error(error.message);
            }
        },
        // 点击修改打开修改窗口的函数
        clickEditButton(row) {
            this.dialogVisible = true;
            this.addUserData = {
                ...this.addUserData,
                id: row.id,
                password: row.password,
                username: row.username,
                nickName: row.nickName,
            };
        },
        // 点击关闭窗口
        closeWindow() {
            this.dialogVisible = false;
            this.addUserData = {
                password: "",
                username: "",
                nickName: "",
            };
        },
        // 点击删除用户
        async deleteUser(id) {
            try {
                await reqDeleteUser(id);
                this.initData();
                this.$notify.success("删除用户成功");
            } catch (error) {
                this.$notify.error(error.message);
            }
        },
        // 表单验证
        submitForm(ruleForm) {
            this.$refs[ruleForm].validate((valid) => {
                if (valid) {
                    this.$notify({
                        title: "提示",
                        message: "校验成功",
                        type: "success",
                    });
                    alert("submit!");
                } else {
                    this.$notify({
                        title: "提示",
                        message: "校验失败",
                        type: "error",
                    });
                    return false;
                }
            });
        },
        // 获取用户角色信息
        async getRoleInfo(row) {
            try {
                this.addUserData = {
                    ...this.addUserData,
                    id: row.id,
                    password: row.password,
                    username: row.username,
                    nickName: row.nickName,
                };
                this.dialogVisibleRole = true;
                const re = await reqGetRoleInfo(row.id);
                this.assignRoles = re.data.assignRoles;
                this.allRolesList = re.data.allRolesList;
                this.allRolesListName = this.allRolesList.map(
                    (item) => item.roleName
                );
                this.assignRolesName = this.assignRoles.map((item) => {
                    // return { name: item.roleName, id: item.id };
                    return item.roleName;
                });
                this.$notify.success("获取角色信息成功");
            } catch (error) {
                this.$notify.error(error.message);
            }
        },
        //  点击确定设置角色提交函数
        async changeUserRole() {
            try {
                const assignIdList = this.allRolesList.reduce((p, c) => {
                    this.assignRolesName.forEach((item) => {
                        if (c.roleName === item) {
                            p.push(c.id);
                        }
                    });
                    return p;
                }, []);
                const data = {
                    userId: this.addUserData.id,
                    roleId: assignIdList,
                };
                await reqChangeUserRole(data);
                this.dialogVisibleRole = false;
                this.$notify.success("设置角色成功");
            } catch (error) {
                this.$notify(error.message);
            }
        },
        // 点击取消设置角色
        cancelChangeUserRole() {
            this.assignRoles = [];
            this.allRolesList = [];
            this.allRolesListName = [];
            this.assignRolesName = [];
            this.dialogVisibleRole = false;
        },
        // 批量删除
        async mutiDeleteUser() {
            try {
                const idList = this.selectedRow.map((item) => item.id);
                await reqMutiDeleteUser(idList);
                this.$notify.success("批量删除成功");
                this.initData();
            } catch (error) {
                this.$notify.error(error.message);
            }
        },
        // 表格选中修改回调
        changeSelect(select, row) {
            this.selectedRow = select;
        },
        // 表格选中所有回调
        changeSelectAll(select) {
            this.selectedRow = select;
        },
    },
    mounted() {
        this.getUserList();
    },
    watch: {
        currentPage() {
            this.initData();
        },
    },
};
</script>

<style>
.text {
    font-size: 14px;
}

.item {
    margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
    display: table;
    content: "";
}
.clearfix:after {
    clear: both;
}

.box-card {
    width: 480px;
}
</style>
